package com.gateway.fliter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证token
 */
@Component
public class VerifyTokenFilter extends ZuulFilter {


    /**
     * 过滤器类型
     * @return
     */
    @Override
    public String filterType() {

        return "post";
    }

    /**
     * 顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 过滤器是否需要执行，true
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 业务代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("------pre类型过滤器正在执行---------");

//        HttpServletRequest request = null;

        //获取HttpServletRequest, 获取请求参数
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes())
                .getRequest();

       String token  = request.getParameter("token");

       System.out.println("-------token---" + token);

        //获取RequestContext
        RequestContext requestContext = RequestContext.getCurrentContext();

        if (StringUtils.isEmpty(token)){

            requestContext.setResponseBody("token为空");

            requestContext.setResponseStatusCode(503);

            requestContext.setSendZuulResponse(false);

            return null;
       }

        //验证token redis中是否存在。 JWT的技术来验证






        return null;
    }
}
